'use strict';

/* Controllers */
// signin controller
app.controller('SigninFormController', ['$rootScope', '$scope', '$state', '$window', 'userService', 'authenticationService', function ($rootScope, $scope, $state, $window, userService, authenticationService) {
    $scope.user = {};
    $scope.authError = null;
    if($window.sessionStorage.userInfo){
        userService.logout($window.sessionStorage.token).then(function (response) {
            $window.sessionStorage.clear();
        }, function (response) {
            $window.sessionStorage.clear();
        });
    }

    $scope.login = function (formInvalid) {
        if(formInvalid==true){
            $scope.authError = '请输入用户名或密码后再登录！';
        }else if (formInvalid == false){
            $scope.authError = null;
            // Try to login
            userService.login($scope.user.email, $scope.user.password)
            .then(function (response) {
                // console.info("SigninFormController.login: ", response);
                if (!response.data.info) {
                    $scope.authError = 'UserName or Password not right';
                } else {
                    if (response.data.Error != null) {
                        $scope.authError = response.data.Error.Message.split('\n')[0];
                        return;
                    }
                    authenticationService.isLogged = true;
                    // $window.sessionStorage.token = response.data.info.Token;
                    $window.sessionStorage.userInfo = response.data.info.userName;
                    $rootScope.$broadcast('SigninFormController:SignedIn', response.data.info.userName);
                    $state.go('app.management.user');
                }
            }, function (x) {
                $scope.authError = 'Server Error';
            });
        }
        
    };
}]);